<template>
    <div class="container">
        <div class="articles-list">
            <div class="table-container">
                <div class="table-header">
                    <h2>
                        文章列表
                    </h2>
                    <el-button type="primary" @click="handleAdd()">添加</el-button>
                </div>
                <el-table :data="tableData" border height="250">
                    <el-table-column prop="createTime" label="日期" width="150">
                        <template slot-scope="scope">
                            {{ formattedDate(scope.row.createTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="title" label="文章名" width="120">
                        <template slot-scope="scope">
                            <div class="table-name">
                                <span>{{ scope.row.title }}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="imageUrl" label="配图" width="120">
                        <template slot-scope="scope">
                            <img class="article-image" :src="scope.row.imageUrl" alt="" />
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="100">
                        <template slot-scope="scope">
                            <el-button @click="handleClick(scope.row.id)" type="text" size="small">查看</el-button>
                            <el-button type="text" size="small" @click="handleDelete(scope.row.id)"
                                style="color: red;">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="article-container">
                <el-form ref="form" :model="form" label-width="80px">
                    <el-form-item label="标题">
                        <el-input v-model="form.title"></el-input>
                    </el-form-item>
                    <el-form-item label="配图">
                        <el-input v-model="form.imageUrl"></el-input>
                    </el-form-item>
                    <el-form-item label="内容">
                        <el-input type="textarea" :autosize="{ minRows: 15, maxRows: 15 }"
                            v-model="form.content"></el-input>
                    </el-form-item>
                    <el-form-item label="标签">
                        <el-checkbox-group v-model="articleTags" size="medium">
                            <el-checkbox v-for="tag in tags" :key="tag.id" :label="tag.name" border></el-checkbox>

                        </el-checkbox-group>
                    </el-form-item>
                    <el-form-item>
                        <div v-if="!isAdd" class="button-container">
                            <el-button @click="handleUpdate(form.id)">更新</el-button>
                            <el-button type="primary" @click="handleRecommend(form.id)">推荐</el-button>
                            <el-button type="warning" @click="handleCancelRecommend(form.id)">取消推荐</el-button>
                        </div>
                        <div v-else>
                            <el-button @click="addNewArticle()">添加</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script>
import { addArticle, getArticleList, getArticle, recommendToSimilarUsers, cancelRecommendations, updateArticle, deleteArticle } from "../api/article";
import { getAllTags } from "../api/tag";
export default {
    name: "PromotionsView",
    data() {
        return {
            isAdd: false,
            tableData: [
                {
                    id: 3,
                    title: "健康饮水指南",
                    content: "每天8杯水...",
                    imageUrl: "http://t15.baidu.com/it/u=2160193551,2816234694&fm=224&app=112&f=JPEG?w=385&h=500",
                    createTime: "2025-05-09T15:17:43.000+08:00",
                    tagIds: null,
                    tags: ['健康']
                },
                {
                    id: 2,
                    title: "健康饮水指南",
                    content: "每天8杯水...",
                    imageUrl: "http://t15.baidu.com/it/u=2160193551,2816234694&fm=224&app=112&f=JPEG?w=385&h=500",
                    createTime: "2025-05-09T15:17:40.000+08:00",
                    tagIds: null,
                    tags: ['健康', '生活']
                }
            ],
            article: {},
            tags: [],
            form: {
                title: "",
                content: "",
                tags: [],
                tagIds: []
            },
            articleTags: [],
            articleTagsId: []
        }
    },
    created() {
        this.fetchData();
    },
    methods: {
        async fetchData() {
            try {
                const articleListRes = await getArticleList();
                this.tableData = articleListRes.data;

                const tagsRes = await getAllTags();
                this.tags = tagsRes.data;

                const articleRes = await getArticle(this.tableData[0].id);
                this.form = articleRes.data;
                this.getTagName(this.form.tags);
            } catch (error) {
                console.error("Error fetching data:", error);
            }
        },
        refreshArticles() {
            getArticleList().then(res => {
                console.log(res);
                this.tableData = res.data;
            })
        },
        getTags() {
            getAllTags().then(res => {
                console.log(res);
                this.tags = res.data;
            })
        },
        getTagName(tags) {
            this.articleTags = tags.map(tag => tag.name);
        },
        getTagId() {
            const t = this;
            this.articleTagsId = this.articleTags.map(name => {
                const tag = t.tags.find(tag => tag.name === name);
                return tag ? tag.id : null;
            });
        },
        handleAdd() {
            this.form = {}
            this.isAdd = true;
        },
        addNewArticle() {
            addArticle(this.form).then(res => {
                console.log(res);
                this.$message.success('添加成功');
                this.refreshArticles();
            })
        },
        handleClick(id) {
            this.isAdd = false;
            getArticle(id).then(res => {
                this.form = res.data;
                this.getTagName(this.form.tags);
            })
        },
        handleDelete(id) {
            deleteArticle(id).then(res => {
                console.log(res);
                this.$message.success('删除成功');
                this.refreshArticles();
            })
        },
        handleUpdate(id) {
            this.getTagId();
            this.form.tagIds = this.articleTagsId;
            updateArticle(id, this.form).then(res => {
                console.log(res);
                this.$message.success('更新成功');
                this.refreshArticles();
            })
        },
        handleRecommend(id) {
            recommendToSimilarUsers(id).then(res => {
                console.log(res);
                this.$message.success('推荐成功');
            })
        },
        handleCancelRecommend(id) {
            cancelRecommendations(id).then(res => {
                console.log(res);
                this.$message.success('取消推荐成功');

            })
        },
        formattedDate(time) {
            const date = new Date(time);
            const year = date.getFullYear();
            const month = date.getMonth() + 1;
            const day = date.getDate();
            return `${year}年${month}月${day}日`;
        }
    }
};
</script>
<style scoped>
.container {
    width: 100%;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

.articles-list {
    padding: 1.5rem;
    width: 80%;
    height: 80%;
    background-color: #ffffff;
    border-radius: 1.75rem;
    box-shadow: 0 0 30px #0a113612;
    display: flex;
    justify-content: space-around;

}

.table-container {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.article-image {
    width: 100px;
    height: 100px;
}

.article-container {
    width: 60%;
    border-left: solid 3px #e6e6e6;
}

.button-container {
    display: flex;
    gap: 20px;
}
</style>